﻿var ajaxDevListUrl = CallNumberUrl+'/VideoPass/selectCallingDeviceList';//获取在线设备列表
var ajaxDeptUrl = CallNumberUrl+'/VideoPass/selectDeptList';
var ajaxCallStatusUrl = CallNumberUrl+'/VideoPass/selectTriageDeviceCallStatus';//分诊台查询并修改勿扰模式
var ajaxCallingUrl = CallNumberUrl+'/VideoPass/CallingShout';
var ajaxTriageUrl =CallNumberUrl+'/VideoPass/selectTriageDeviceList';//所有在线的分诊台列表
var triagePositionUrl = TriageUrl+'/Triage/getBackTriageInfo';//获取位置信息
var timer = 1000 * 60;//进入对讲模块刷新数据、每隔1分钟自动刷新数据
var t = null;

var undergraduateDeptId = "";//本科室ID
var selectedDeptId = "";//选中后科室ID



$(function () {
    var deptId = getCookie('deptId');
    var deptName = unescape(getCookie("deptName")||'');
    $('#deptId').val(deptId);
    selectedDeptId = deptId;
    undergraduateDeptId = deptId;
    var _callStatus = localStorage.getItem('callStatus');
    if(_callStatus == 1) $('#callStatus').prop('checked',true);
    // 科室选择  失去焦点不能隐藏，原因是 选择科室的时候 就会自动失去焦点
    $('#ipt-dept').on('focus',function () {
        $('#side').show().find('dl,ol').hide();
        $('.mask').show();
    }).val(deptName||'').on('input',function () {
        getDeptList();
    });
    $('.mask').on('click',function () {
        var val = $('#ipt-dept').val();
        var _html = $('#side').html();
        var lens = $('#side .layui-icon-radio').length;
        // 当输入框没有值  or 没有查询结果 or 沒有选择
        if(val==''||_html==''||lens<1){
            $('#ipt-dept').val('');
            getDeptList();
            return layer.msg('请选择科室',{icon:0});
        };
        // 兼容 切换科室但是没有选的情况
        invertedShow()
        $('#side').hide();
        $(this).hide();
    });
    /***
     * 科室选中逻辑
     ***/
    $('#side').on('click','.Level_1 span',function () {
        $('#side li').removeClass('active');
        $(this).parents('li').addClass('active');
        $('#side div:not(:first-child),#side div:not(:first-child) ul').hide();
        if($(this).hasClass('mui-icon-right')){
            var cid = $(this).parents('li').attr('cid');
            $('#side div:nth-child(2)').show().find('ul#pid_'+cid).show();
        }else {
            // 隐藏下一级
            $(this).parents('div[class^="Level_"]').nextAll('div').hide();
        }

    }).on('click','.Level_2 span',function () {
        $('.Level_2 li,.Level_3 li').removeClass('active');
        $(this).parents('li').addClass('active');
        $('#side div:last-child ul').hide();
        if($(this).hasClass('mui-icon-right')){
            var cid = $(this).parents('li').attr('cid');
            $('#side div:last-child').show().find('ul#pid_'+cid).show();
        }else {
            // 隐藏下一级
            $(this).parents('div[class^="Level_"]').next('div').hide();
        }

    }).on('click','i.layui-icon',function () {
        // 先清除所有选中状态
        $(this).parents('#side').find('.layui-icon').removeClass('layui-icon-radio').addClass('layui-icon-circle');
        // 在设置当前的 li 选中状态 清除 当前级别其他 li 的选中状态
        $(this).parents('li').addClass('active').siblings().removeClass('active');
        // 单选框的选中状态
        $(this).removeClass('layui-icon-circle').addClass('layui-icon-radio');
        // 隐藏下一级
        $(this).parents('div[class^="Level_"]').next('div').hide();
        // 获取科室诊室名称
        var deptName =  $(this).siblings('span').text();
        var deptId = $(this).parents('li').attr('cid');
        // 隐藏遮罩层
        $('#side').hide().find('dl,ol').hide();
        $('.mask').hide();
        // 设置值
        $('#ipt-dept').val(deptName);
        $('#deptId').val(deptId);
        selectedDeptId = deptId;
        // 开始搜索
        getDevList(deptId);
        getTriageData(deptId);
    });
    triagePositionStr();
    refresh();
    switchStatus();
    getDeptList();
    t = setTimeout(setTimers,timer);

});
function invertedShow() {
    $('#side li').removeClass('active');
    $('.Level_2,.Level_3').hide();
    var className = $('#side .layui-icon-radio').parents('div').attr('class');
    if(className!='Level_1'){
        var arr = $('#side .layui-icon-radio').parents('ul').attr('id').split('_');
        if(className=='Level_2'){
            $('#cid_'+arr[1]).addClass('active').find('span').trigger('click');
        }else {
            $('#cid_'+arr[1]).addClass('active');
            var parr =  $('#cid_'+arr[1]).parents('ul').attr('id').split('_');
            $('#cid_'+parr[1]).addClass('active').find('span').trigger('click');
            $('#cid_'+arr[1]).find('span').trigger('click');
        }
        $('#side .layui-icon-radio').parents('li').addClass('active');
    }else {
        $('#side .layui-icon-radio').parents('li').addClass('active');
    }


}
/**
 * 分诊台列表中获取到位置信息-positionStr
 * 缓存下来为呼叫操作接口赋值-name
 */
function triagePositionStr() {
    $.ajax({
        url:triagePositionUrl,
        type:"get",
        data:{
            triageId:getDeviceId()
        },
        success:function (d) {
            if (JSON.parse(d).status == '0') {
                var dataInfo = JSON.parse(d).data;
                var _positionStr = dataInfo.positionStr;
                localStorage.setItem("triagePositionStr", _positionStr);
            }
        }
    });
}

/***
 *  每隔1分钟自动刷新数据
 * */
function setTimers() {
    refresh();
    clearTimeout(t);
    t = null;
    t = setTimeout(setTimers,timer);
}

/**
 * 刷新
 */
function refresh() {
    var deptId = $('#deptId').val();
    getDevList(deptId);
    getTriageData();
}


/**
 * 在线诊室列表
 */
function getDevList(deptId) {
    layer.load(1, {
        shade: [0.1,'#fff'] //0.1透明度的白色背景
    });
    $.ajax({
        url:ajaxDevListUrl,
        type:'get',
        data:{
            deptId:deptId
        },
        success:function (d) {
            try{
                d = JSON.parse(d);
            }catch (e) {

            }
            if(d.status == "0"){
                if(d.data&&d.data.length>0){
                    var frag =  dealDevList(d.data);
                    $('#devListsTbody').show().html(frag);
                    $('.mui-empty').hide();
                }else {
                    $('#devListsTbody').hide();
                    $('.mui-empty').show();
                }

            }else{
                layer.alert(d.desc,{icon:2});
            }
        },
        complete: function () {
            layer.closeAll();
        }
    });
}

/**
 * 处理在线诊室列表数据
 *  @param arr
 * **/
function dealDevList(arr) {
    var devId = getDeviceId();
    arr = arr ||[];
    var frag = '';
    for (var i=0;i<arr.length;i++){
        if(!arr[i]||arr[i]==''||arr[i]['callingDeviceId']==devId) continue;
        frag +='<tr>';
        frag +='<td>'+arr[i]['callingRelationObjName']+'</td>';
        frag +='<td>'+arr[i]['loginName']+'</td>';
        frag +='<td><span onclick=calling("'+arr[i]['loginName']+'","'+arr[i]['callingDeviceId']+'","0")>呼叫</span></td>';
        frag +='</tr>';
    }
    return frag;
}

/**
 * 呼叫操作
 * @param loginName
 * @param devId
 * @param type
 */
function calling(loginName,devId,type) {
    var params = {
        hospitalId:getHospitalId(),
        deviceId:getDeviceId(),
        deptName:unescape(getCookie("deptName")),
        name:localStorage.getItem("triagePositionStr"),
        callName:loginName,
        deviceType:1, // 呼叫类型
        callDeviceType:type, //接收端 类型  默认叫号器  1 分诊台
        callDeptName:$('#ipt-dept').val(),
        callDeviceId:devId
    };
    $.ajax({
        url:ajaxCallingUrl,
        type:"POST",
        headers: {
            'Content-Type': 'application/json'
        },
        data:JSON.stringify(params),
        success:function (res) {
            if(res.status == "0"){
                try{
                    my_cefsharp.Open_CallMain(JSON.stringify(res.data));
                }catch (e) {
                    layer.msg(res.desc,{icon:0});
                }
            }else {
                layer.msg(res.desc,{icon:0});
            }
        }
    });
}

/****
 *   获取科室树
 *   1、查询结果默认不区分级别
 *   2、当1级和二级中有相同的字的时候会展示二级
 *   3、当查询结果只有一级的时候不会带有子集
 *
 * **/
function getDeptList(){
    var deptName = $('#ipt-dept').val();
    $.ajax({
        url:ajaxDeptUrl,
        type:'get',
        data:{
            deptName:deptName
        },
        success:function (d) {
            try{
                d = JSON.parse(d);
            }catch (e) {

            }
            if(d.status == "0"){
                $("#side").html('');
                dealDeptTree(d.data);
            }else{
                layer.alert(d.desc,{icon:2});
            }
        }
    });
}
/**
 *  处理科室树
 *  @param arr
 * **/
function dealDeptTree(arr) {
    arr = arr || [];
    var pidObj = dealPidGroup(arr),levelObj = {},temp = {
        Level_1:{},
        Level_2:{},
        Level_3:{},
    };
    var deptId = $('#deptId').val();
    console.log('deptId------'+deptId)
    for (var i = 0; i < arr.length; i++) {
        if(pidObj['pid_'+arr[i]['deptId']]){
            arr[i]['child'] = pidObj['pid_'+arr[i]['deptId']]
        }
        if(!levelObj['Level_'+arr[i].deptLevel]){
            levelObj['Level_'+arr[i].deptLevel] = []
        }
        if(deptId==arr[i].deptId){
            levelObj['Level_'+arr[i].deptLevel].push({
                deptId:arr[i].deptId,
                parentId:arr[i].parentId,
                checked:true,
                deptName:arr[i].deptName,
                child:arr[i]['child']||[],
            });
        }else {
            levelObj['Level_'+arr[i].deptLevel].push({
                deptId:arr[i].deptId,
                parentId:arr[i].parentId,
                checked:false,
                deptName:arr[i].deptName,
                child:arr[i]['child']||[],
            });
        }
    }
    for (var k in temp){
        temp[k] = dealPidGroup(levelObj[k])
    }
    console.log(temp)
    dealNodeLists(temp)
}

/**
 *  展示数据
 *  @param obj  Object
 * */
function dealNodeLists(obj) {
    obj = obj ||{};
    var frag = '',temp,arr;
    for (var k in obj){
        if(JSON.stringify(obj[k])=='{}') continue;
        frag +='<div class="'+k+'">';
        temp = obj[k];
        for (var z in temp){
            frag +=' <ul id="'+z+'">';
            arr = temp[z];
            for (var i = 0;i<arr.length;i++){
                if(arr[i]['child'].length>0){
                    if(arr[i]['checked']){
                        frag +='<li id="cid_'+arr[i]['deptId']+'" cid="'+arr[i]['deptId']+'" class="active"><i class="layui-icon layui-icon-radio"></i><span class="mui-icon-right">'+arr[i]['deptName']+'</span></li>';
                    }else {
                        frag +='<li id="cid_'+arr[i]['deptId']+'" cid="'+arr[i]['deptId']+'"><i class="layui-icon layui-icon-circle"></i><span class="mui-icon-right">'+arr[i]['deptName']+'</span></li>';
                    }
                }else {
                    if(arr[i]['checked']){
                        frag +='<li id="cid_'+arr[i]['deptId']+'" cid="'+arr[i]['deptId']+'" class="active"><i class="layui-icon layui-icon-radio"></i><span>'+arr[i]['deptName']+'</span></li>';
                    }else {
                        frag +='<li id="cid_'+arr[i]['deptId']+'" cid="'+arr[i]['deptId']+'"><i class="layui-icon layui-icon-circle"></i><span>'+arr[i]['deptName']+'</span></li>';
                    }
                }
            }
            frag +='</ul>';
        }
        frag +='</div>';
    }
    $('#side').html(frag);
}
/**
 *  科室按照 pid 分组
 *  @param arr
 * **/
function dealPidGroup(arr) {
    arr = arr ||[];
    var pidObj = {};
    for (var i = 0; i < arr.length; i++) {
        if(!pidObj['pid_'+arr[i].parentId]){
            pidObj['pid_'+arr[i].parentId] = [];
        }
        pidObj['pid_'+arr[i].parentId].push({
            deptId:arr[i].deptId,
            checked:arr[i].checked,
            parentId:arr[i].parentId,
            deptName:arr[i].deptName,
            child:arr[i]['child']||[],
        });
    }
    return pidObj;
}

/**
 * 点击呼叫分诊台操作按钮操作
 */
function openLayerTriage() {
    layer.open({
        type: 1,
        shade: false,
        area: [ '320px','420px'], //宽高
        title: '请选择分诊台', //是否显示标题
        content: $('#triageList'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
    });
}


/**
 * 医护对讲弹框-分诊台列表
 */

function getTriageData() {
    $.ajax({
        url:ajaxTriageUrl,
        type:"get",
        data:{
            deptId:$("#deptId").val()
        },
        success:function (d) {
        var triageData = "";
            if(typeof d == "string"){
                triageData = JSON.parse(d);
            }else{
                triageData = d;
            }
            if(triageData.status == 0){
                var triageListData = triageData.data;
                if(triageListData && triageListData.length > 0 && undergraduateDeptId != selectedDeptId){
                    $('#triages').show();
                    var triageHtml = "";
                    for(var i = 0; i < triageListData.length; i++){
                        var _positionStr = triageListData[i].positionStr ? triageListData[i].positionStr : "";//诊室
                        var _loginStatus = triageListData[i].loginStatus;//登录状态
                        triageHtml += '<ul class="layui-clear">';
                        triageHtml += '<li>'+ _positionStr +'</li>';
                        if(_loginStatus == "0"){
                            triageHtml += '<li><span class="succ">在线</span></li>';
                            triageHtml += '<li><button onclick=calling("'+triageListData[i]['positionStr']+'","'+triageListData[i]['triageId']+'","1") type="button" class="layui-btn layui-btn-sm">呼叫</button></li>';
                        }else {
                            triageHtml += '<li><span class="succ">离线</span></li>';
                            triageHtml += '<li><button type="button" class="layui-btn layui-btn-disabled layui-btn-sm">呼叫</button></li>';
                        }

                        triageHtml += '</ul>';
                    }
                    $("#triageList").html(triageHtml);
                }else{
                    $('#triages').hide();
                }
            }else{
                layer.open(triageData.desc,{icon:2});
            }
        }
    });
}

/**
 *监听勿扰模式
 */
function switchStatus() {
    layui.use(['form','jquery'], function(){
        var form = layui.form;
        //监听勿扰模式开关
        form.on('switch(status)', function(data){
            switchCalling(this.checked);
        });
        form.render();
    });
}

/**
 * 分诊台查询并修改勿扰模式
 * @param type ==== 0:关闭 1：开启
 */
function switchCalling(type) {
    var status = type?1:0;
    $.ajax({
        url:ajaxCallStatusUrl,
        type:"get",
        data:{
            deviceId:getDeviceId(),
            disturbStatus:status
        },
        success:function (res) {
            if(res.status == "0"){
                if(isDisableCall) isDisableCall(type);
            }else {

            }
        }
    });
}
